<?php
/**
 * 
 * usage : 
 * 1)A basic use:
 * $bm = WF::getBenchmarkFactory()->getBenchmark();
 * //code here
 * echo $bm->elapsed() . " Seconds";
 * //note that 'start' was auto generated
 *
 * 2)Another use where we use other markers for something like sending an email
 * $bm = WF::getBenchmarkFactory()->getBenchmark();
 * $bm->mark('email_start');
 * //email code here
 * $bm->mark('email_stop');
 * echo $bm->elapsed('email_start', 'email_stop') . " Seconds";
 * 
 * 3)Using it as a totalizer
 * $bm = WF::getBenchmarkFactory()->getBenchmark();
 * $total_time = 0;
 * foreach($emails as $email){
 * 		$bm->mark('email_start');
 * 		//email code here
 * 		$bm->mark('email_stop');
 * 		$total_time += $bm->elapsed('email_start', 'email_stop');
 * }
 * echo $total_time . " Seconds";
 */
class WFBenchmark {
	private $marker = array(); //internal marker array
    	/**
         *\brief Description
         *  - Set the first marker
         */
		public function __construct() {
			$this->marker['start'] = microtime(true);
		}
		/**
         *\brief Description
         *  - Set a marker
         */
		public function mark($name) {
			$this->marker[$name] = microtime(true);
		}
    	/**
         *\brief Description
         *  - Calculate elapsed time between two points
         */
		public function elapsed($point1 = 'start', $point2 = 'end', $decimals = 4) {
		    if($point1 == 'start' && isset($this->marker['start']) && $point2 == 'end' && !isset($this->marker['end'])){
		        $this->mark('end');
		    }			
			$ret = number_format($this->marker[$point2] - $this->marker[$point1], $decimals);
			$this->mark('start'); //refrest start marker
			unset($this->marker['end']);
			return $ret;
		}
}